const THREAD_COUNT = 32;
const CHUNK_SIZE = 10 * 1024 * 1024; // 10MB per chunk
const FILE_URL = 'https://yun.mcloud.139.com/hongseyunpan/2.43G.zip';
let activeWorkers = 0;
let totalChunks = 0;
let completedChunks = 0;
let downloadStartTime = 0;
let fileSize = 0;
let isDownloading = false;

// 创建Web Worker代码
const workerCode = `
    self.onmessage = async function(e) {
        const { url, start, end, index } = e.data;
        try {
            const response = await fetch(url, {
                headers: { 'Range': 'bytes=' + start + '-' + end }
            });
            if (!response.ok) throw new Error('HTTP error! status: ' + response.status);
            const chunk = await response.blob();
            self.postMessage({ type: 'success', index, chunk });
        } catch (error) {
            self.postMessage({ type: 'error', index, error: error.message });
        }
    };
`;

// 创建Blob URL
const workerBlob = new Blob([workerCode], { type: 'application/javascript' });
const workerUrl = URL.createObjectURL(workerBlob);

// 更新进度条
function updateProgress(percent) {
    document.getElementById('status').textContent = 
        `已完成: ${percent.toFixed(2)}% (${completedChunks}/${totalChunks}块)`;
}

// 开始下载
async function startDownload() {
    if (isDownloading) return;
    
    isDownloading = true;
    const startBtn = document.getElementById('startBtn');
    startBtn.disabled = true;
    downloadStartTime = Date.now();

    try {
        // 获取文件大小
        const response = await fetch(FILE_URL, { 
            method: 'HEAD',
            mode: 'cors',
            headers: {
                'Access-Control-Request-Method': 'HEAD',
                'Access-Control-Request-Headers': 'content-length'
            }
        });
        
        if (!response.ok) throw new Error('无法获取文件信息: ' + response.status);
        
        const contentLength = response.headers.get('content-length');
        if (!contentLength) throw new Error('服务器未返回文件大小信息');
        
        fileSize = parseInt(contentLength);
        if (isNaN(fileSize) || fileSize <= 0) throw new Error('文件大小无效');
        
        totalChunks = Math.ceil(fileSize / CHUNK_SIZE);
        const fileSizeMB = (fileSize / (1024 * 1024)).toFixed(2);
        document.getElementById('status').textContent = `准备下载: 文件大小 ${fileSizeMB}MB (${totalChunks}个分片)`;

        // 创建workers并开始下载
        const chunks = new Array(totalChunks);
        for (let i = 0; i < Math.min(THREAD_COUNT, totalChunks); i++) {
            downloadChunk(i, chunks);
        }
    } catch (error) {
        document.getElementById('status').textContent = '下载失败: ' + error.message;
        startBtn.disabled = false;
        isDownloading = false;
    }
}

// 下载单个分片
function downloadChunk(index, chunks) {
    const worker = new Worker(workerUrl);
    activeWorkers++;

    const start = index * CHUNK_SIZE;
    const end = Math.min(start + CHUNK_SIZE - 1, fileSize - 1);

    worker.postMessage({
        url: FILE_URL,
        start,
        end,
        index
    });

    worker.onmessage = function(e) {
        const { type, index, chunk, error } = e.data;
        if (type === 'success') {
            chunks[index] = chunk;
            completedChunks++;
            const progress = (completedChunks / totalChunks) * 100;
            updateProgress(progress);
            
            // 显示下载速度
            const elapsedTime = (Date.now() - downloadStartTime) / 1000;
            const downloadedSize = (completedChunks * CHUNK_SIZE) / (1024 * 1024); // MB
            const speed = downloadedSize / elapsedTime; // MB/s
            
            document.getElementById('status').textContent = 
                `已下载: ${downloadedSize.toFixed(2)}MB | 速度: ${speed.toFixed(2)}MB/s`;

            if (completedChunks === totalChunks) {
                finishDownload(chunks);
            }
        } else {
            document.getElementById('status').textContent = '下载失败: ' + error;
            isDownloading = false;
        }

        worker.terminate();
        activeWorkers--;

        // 如果还有未开始的分片，继续下载
        if (activeWorkers < THREAD_COUNT && completedChunks < totalChunks) {
            const nextIndex = chunks.findIndex(chunk => chunk === undefined);
            if (nextIndex !== -1) {
                downloadChunk(nextIndex, chunks);
            }
        }
    };
}

// 完成下载
async function finishDownload(chunks) {
    const blob = new Blob(chunks);
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = '2.43G.zip';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    const downloadTime = (Date.now() - downloadStartTime) / 1000;
    document.getElementById('status').textContent = 
        `下载完成! 用时: ${downloadTime.toFixed(2)}秒`;
    
    // 重置状态
    isDownloading = false;
    completedChunks = 0;
    activeWorkers = 0;
    document.getElementById('startBtn').disabled = false;
    
    // 自动开始新的下载
    setTimeout(startDownload, 1000);
}

// 添加事件监听
document.addEventListener('DOMContentLoaded', function() {
    document.addEventListener('keydown', function(event) {
        if (!isDownloading) {
            startDownload();
        }
    });

    document.addEventListener('mousedown', function(event) {
        if (!isDownloading && (event.button === 0 || event.button === 2)) {
            startDownload();
        }
    });

    // 禁用右键菜单
    document.addEventListener('contextmenu', function(event) {
        event.preventDefault();
    });
});